package model

import (
	"context"

	"code.bydev.io/cht/asset/common-utils.git/ugorm"
	"code.bydev.io/cht/customer/kyc_admin_service/internal/utils"
	"code.bydev.io/frameworks/byone/core/stores/sqlx"
	"emperror.dev/errors"
	"gorm.io/gorm"
)

const (
	KycDB    = "KycDB"    // KycDB
	KycNewDB = "KycNewDB" // NewKYC
)

type Config struct {
	KycDB    sqlx.Config
	KycNewDB sqlx.Config
}

func InitDB(c *Config) {
	err := ugorm.NewGorm(KycDB, c.KycDB)
	utils.CheckInitError(err)
	err = ugorm.NewGorm(KycNewDB, c.KycNewDB)
	utils.CheckInitError(err)
}

func DBKyc(ctx context.Context) *gorm.DB {
	return ugorm.GetORM(ctx, KycDB)
}

// DBBKycNew 获取DB连接
func DBBKycNew(ctx context.Context) *gorm.DB {
	return ugorm.GetORM(ctx, KycNewDB)
}

// BeginKycDBTransaction 启动事务
func BeginKycDBTransaction(ctx context.Context) (*gorm.DB, error) {
	db := ugorm.GetORM(ctx, KycDB)
	if db == nil {
		return nil, errors.New(KycDB + ":DB Is nil")
	}
	return db.Begin(), nil
}

func KycDBTransaction(ctx context.Context, fn func(tx *gorm.DB) error) error {
	db := ugorm.GetORM(ctx, KycDB)
	if db == nil {
		return errors.New(KycDB + ":DB Is nil")
	}
	return db.Transaction(fn)
}

func BeginKycNewDBTransaction(ctx context.Context, fn func(tx *gorm.DB) error) error {
	db := ugorm.GetORM(ctx, KycNewDB)
	if db == nil {
		return errors.New(KycNewDB + ":DB Is nil")
	}
	return db.Transaction(fn)
}
